import { useEffect, useState, FC } from 'react';
import * as I from '@ant-design/icons'
import style from './index.module.less'
import { useSelector, useDispatch } from 'react-redux';
import { INIT_TAB_STATE } from '@src/redux/reducers/tab';
import { Dispatch } from 'redux';
import { addWindow } from '@redux/actions/tab'
import { WindowSchema } from '@src/components/schema/window';
import { UserInfo } from '@src/components/schema/basic';
import { INIT_BASIC_STATE } from '@redux/reducers/basic';
import { MenuSchema } from '@src/components/schema/menu';
import classNames from 'classnames';

const ICONS: { [k: string]: FC<{[k: string]: any}> } = I as unknown as { [k: string]: FC }

/**
 * 子菜单是否展示中
 */
function isChildrenSelected (list: MenuSchema[] | undefined, activeWindowId: string) {
  if (!list) {
    return ''
  }
  const goal = list.find(li => li.id === activeWindowId)
  return goal ? style.active : ''
}

// 是否展开菜单
function toggleFirstMenu (list: MenuSchema[] ,index: number, dispatch: Dispatch, setMenus: (v: MenuSchema[]) => void) {
  const menus = list.slice()
  const menu = menus[index]
  if (menu.children && menu.children.length > 0) {
    menu.showChildren = !menu.showChildren
    setMenus(menus)
  } else {
    openPage(dispatch, menu)
  }
}

function initDesktop (windows: WindowSchema[], userInfo: UserInfo, dispatch: Dispatch) {
  const { id, desktop } = userInfo
  if (id && windows.length === 0) {
    dispatch(addWindow({ id: '0', title: '桌面', componentName: desktop || 'DesktopDefault', closable: false, isHome: true }))
    // dispatch(addWindow({
    //   "id": "document-sign-21A2E6CE7F3AB63E5DB5EE9403EBC1A3",
    //   "title": "仲裁文书签发表",
    //   "componentName": "PdfSignReader",
    //   "forceRefresh": false,
    //   "meta": {
    //     "id": "21A2E6CE7F3AB63E5DB5EE9403EBC1A3",
    //     "editable": true,
    //     "caseid": "1A9A9E1C4E17C8977391925216880D67"
    //   }
    // }))
  //   dispatch(addWindow({ componentName: "PdfReader",
  // id: "视频开庭笔录模板-BE211941E64E3D15391CC1BAF28C8AB4",
  // meta: {caseid: '1A9A9E1C4E17C8977391925216880D67', fileid: 'BE211941E64E3D15391CC1BAF28C8AB4', readonly: false},
  // title: "视频开庭笔录模板" }))
  }
}

function openPage (dispatch: Dispatch, menu: MenuSchema) {
  dispatch(addWindow({ id: menu.id, title: menu.title, componentName: menu.componentName, closable: true, meta: {}, isHome: false }))
}

interface Props {
  data: MenuSchema[]
}

function Main ({ data }: Props) {
  const [menus, setMenus] = useState<MenuSchema[]>([])
  const dispatch = useDispatch()
  const { activeWindowId, windows, userInfo }  = useSelector((state: { tab: INIT_TAB_STATE, basic: INIT_BASIC_STATE }) => {
    return {
      activeWindowId: state.tab.activeWindowId,
      windows: state.tab.windows,
      userInfo: state.basic.userInfo
    }
  })
  useEffect(() => {
    setMenus(data)
  }, [data])
  useEffect(() => {
    initDesktop(windows, userInfo, dispatch)
  }, [])
  return (
    <div>
      {
        menus.map((menu, i) => {
          let Icon
          const blockClass = [style.menu__firstMenu]
          if (menu.icon) {
            Icon = ICONS[menu.icon]
          } else {
            blockClass.push(style['no-icon'])
          }
          const Arrow = menu.showChildren ? ICONS.UpOutlined : ICONS.DownOutlined
          return (
            <li key={menu.id} className={isChildrenSelected(menu.children, activeWindowId)}>
              <div className={blockClass.join(' ')}>
                <div onClick={() => toggleFirstMenu(menus, i, dispatch, setMenus)}>
                  {Icon ? <div className={style.menu__icon}><Icon /></div> : null}
                  <span className={classNames(style.firstmenu__title, { [style.active]: menu.id === activeWindowId, [style['no-children']]: menu.children.length === 0 })}>{menu.title}</span>
                  {
                    menu.children.length > 0 && (
                      <div className={style.menu__direction}>
                        {<Arrow className={style['menu__direction-icon']} />}
                      </div>
                    )
                  }
                </div>
                {menu.showChildren && menu.children instanceof Array && (
                  <ul className={style['sub-menu']}>
                    {
                      menu.children.map(item => {
                        const activeClass = item.id === activeWindowId ? style.active : ''
                        return (
                          <li className={activeClass} key={item.id} onClick={() => openPage(dispatch, item)}>{item.title}</li>
                        )
                      })
                    }
                  </ul>
                )}
              </div>
            </li>
          )
        })
      }
    </div>
  ) 
}

export default Main
